<?php
/**
 * (新)备货
 * (model)
 */
namespace App\Models\ProductStockup;

use App\Models\Basics\SysArea;
use App\Models\Inventory\PublicCn;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use App\Models\SalesReport\DailyVolume;
use App\Models\SsBasic\AreaSku;
use App\Models\SsBasic\AreaSkuAvg;
use App\Models\SsBasic\AreaSkuEstimate;
use App\Models\SsBasic\AreaSkuStock;
use App\Models\SsBasic\StockupAreaSkuEstimate;
use App\Models\Stocking\StockingSetDate;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Stockup extends Model{

    protected $table = 'product_stockup';

    protected $guarded = [];

    const STATUS_APPLY_NO  = 0; //未申请(初始状态)
    const STATUS_APPLY     = 1; //申请中（已申请）
    const STATUS_CANCEL    = 2; //撤回申请
    const STATUS_REJECT    = 3; //审核驳回
    const STATUS_APPROVE   = 4; //审核通过
    const STATUS_CONFIRM   = 5; //已确认
    /**
     * 申请状态
     * @var string[]
     */
    public static $APPLY_STATUS = [
        self::STATUS_APPLY_NO   => '未申请',
        self::STATUS_APPLY      => '已申请',
        self::STATUS_CANCEL     => '撤回申请',
        self::STATUS_REJECT     => '审核驳回',
        self::STATUS_APPROVE    => '审核通过',
        self::STATUS_CONFIRM    => '已确认',
    ];

    public static $_status = [
        1 => '已审核',
        2 => '已关闭',
    ];

    /**
     * 地区sku
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function area_sku(){
        return $this->belongsTo(AreaSku::class,'area_psku','area_psku');
    }

    /**
     * 地区sku库存
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function area_stock(){
        return $this->belongsTo(AreaSkuStock::class,'area_psku','area_psku');
    }

    /**
     * 地区sku销售趋势(平均值)
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function area_sku_avg(){
        return $this->belongsTo(AreaSkuAvg::class,'area_psku','area_psku');
    }

    /**
     * 地区sku预估销量
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function area_sku_estimate(){
        return $this->belongsTo(AreaSkuEstimate::class,'area_psku','area_psku');
    }

    /**
     * 地区
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function area(){
        return $this->belongsTo(SysArea::class,'area_id');
    }

    /**
     * sku
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function sku(){
        return $this->belongsTo(ProductSku::class,'psku_id');
    }

    /**
     * classify
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function classify(){
        return $this->belongsTo(ProductClassify::class,'classify_id');
    }

    public function skuClassify(){
        return $this->hasOneThrough(
            ProductClassify::class,
            ProductSku::class,
            'id',//中间表
            'id',//目标表
            'psku_id',//当前模型
            'classify_id'//中间表
        );
    }

    /**
     * 获取指定SQL字段总量
     * @param $classifyId
     * @param $columnField
     * @param null $status
     * @return int|mixed
     */
    public static function getStockupColumnSum($classifyId = null, $columnField = null, $status = null){

        $query = self::query();
        if ($classifyId) {
            $query->where('classify_id', $classifyId);
        }
        if ($status) {
            $query->where('status', $status);
        }
        return $query->sum($columnField);
    }

    /**
     * 获取品类预估总量（站点）
     * @param $classifyId
     * @param $areaId
     * @param $columnField
     * @return int|mixed
     */
    public static function getClassifyEstimateArea($classifyId, $areaId, $columnField){
        $query = self::query();
        if ($classifyId) {
            $query->where('classify_id', $classifyId);
        }
        if ($areaId) {
            $query->where('area_id', $areaId);
        }
        return $query->sum($columnField);
    }


    /**
     * 品类下的sku
     * @param $classify_id
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getClassifySku($classify_id){

        list($sqlTitle, $sqlValue, $sql) = self::setSqlColumn();

        $query = self::query();
        $query->select(DB::raw($sql));
        if ($classify_id) {
            $query->where('classify_id', $classify_id);
        }
        $query->groupBy('psku_id');

        return $query->get();
    }

    /**
     * 品类下的站点
     * @param $classify_id
     * @param null $status
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getClassifyArea($classify_id, $status = null){

        list($sqlTitle, $sqlValue, $sql) = self::setSqlColumn();

        $query = self::query();
        $query->select(DB::raw($sql));
        if ($classify_id) {
            $query->where('classify_id', $classify_id);
        }
        if ($status) {
            $query->where('status', $status);
        }

        $query->groupBy('area_id');

        return $query->get();
    }

    /**
     * (品类下站点的sku
     * @param $classify_id
     * @param $area_id
     * @param null $status
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getClassifyAreaSku($classify_id, $area_id, $status = null){
        $query = self::query();
        if ($classify_id) {
            $query->where('classify_id', $classify_id);
        }
        if ($area_id) {
            $query->where('area_id', $area_id);
        }
        if ($status) {
            $query->where('status', $status);
        }
        $query->groupBy('psku_id');

        return $query->get();
    }

    /**
     * 到最快可售日期时的总需求量(备货周期以外的)
     * @param $model
     * @param $saleDays
     * @return float|int
     */
    public static function _getAvailableEstimateNum($model,$saleDays){
        $initDay = date('j');//当前月第N天
        $j = 0;//到可售周期预估月
        $count = 0;
        $thisDays = 0;//预估月的天数
        $daysTotal = 0;//到最快可售日期所在预估月的总天数
        for($i = 0; $i < AreaSkuEstimate::ESTIMATE_NUM; $i++){
            $thisDays = date('t',strtotime("midnight first day of +{$i} month"));//当月共多少天
            $daysTotal += $thisDays;
            $day = $daysTotal - $initDay;
            if($day >= $saleDays){
                $j = $i;
                break;
            }
            $count++;
        }
        $initDays = date('t');//当前月总天数
        $sum0 = floor($initDay / $initDays * $model->estimate_num0);
        if($count == AreaSkuEstimate::ESTIMATE_NUM){//可售周期过长，需求量 = 总预估量-过期的预估量
            $sum = 0;
            for ($k = 0; $k < $count; $k++){
                $sum += $model->{'estimate_num'.$k};
            }
            $sum -= $sum0;
        }else{//可售周期在预估内
            $kDay = date('j',strtotime("+{$saleDays} days"));//到最快可售天数所在月的当月第N天
            if($j == 0){ //可售周期在当前月，需求量=到最快可售日期的预估量-过期的预估量
                $sum = floor($kDay / $thisDays * $model->estimate_num0) - $sum0;
            }else{//可售周期不在当前月，需求量=到可售周期预估月（$j）-过期的预估量-（$j）多余的预估量
                $sum1 = 0;
                for ($l = 0; $l < $j; $l++){
                    $sum1 += $model->{'estimate_num'.$l};
                }
                $sum2 = floor($kDay / $thisDays * $model->{'estimate_num'.$j});
                $sum = $sum1 + $sum2 - $sum0;
            }
        }
        return $sum;
    }

    /**
     * 初始查询字段
     * @return array
     */
    public static function setSqlColumn(){

        $title1 = [
            'classify_id' => 'classify_id',      //品类ID
            'area_id'     => 'area_id',          //站点ID
            'psku_id'     => 'psku_id',          //产品ID
            'avg3'        => 'sum(avg3) as avg3',     //3天avg
            'avg7'        => 'sum(avg7) as avg7',     //7天avg
            'avg15'       => 'sum(avg15) as avg15',   //15天avg
            'avg30'       => 'sum(avg30) as avg30',   //30天avg
            'avg'         => 'sum(avg) as avg',       //avg

            'current_sale_ratio'    => 'sum(current_sale_ratio) as current_sale_ratio', //旺季销售比例
            'volume3_avg'           => 'sum(volume3_avg) as volume3_avg',         //近3天平均销量
            'volume30_avg'          => 'sum(volume30_avg) as volume30_avg',         //近30天平均销量
            'volume30_ratio'        => 'sum(volume30_ratio) as volume30_ratio',         //近30天销售比例
            'ratio'                 => 'sum(ratio) as ratio',                           //确定后的销售比例
            'estimate_total'        => 'sum(estimate_total) as estimate_total',     //预估总量
            'estimate_growth_rate'  => 'sum(estimate_growth_rate) as estimate_growth_rate', //同期增长率

            'abroad_recommend_num'  => 'sum(abroad_recommend_num) as abroad_recommend_num',   //推荐海外仓发货数量
            'abroad_reality_num'    => 'sum(abroad_reality_num) as abroad_reality_num',  //实际海外仓发货数量
            'recommend_num'         => 'sum(recommend_num) as recommend_num',  //推荐备货数量
            'recommend_remark'      => 'recommend_remark as recommend_remark', //推荐说明
            'apply_num'             => 'sum(apply_num) as apply_num',  //申请数量
            'apply_remark'          => 'apply_remark as apply_remark', //申请备注
            'approval_num'          => 'sum(approval_num) as approval_num',  //审批数量
            'approval_remark'       => 'approval_remark as approval_remark', //审批备注
            'confirm_num'           => 'sum(confirm_num) as confirm_num',  //确认数量
            'confirm_remark'        => 'confirm_remark as confirm_remark', //确认备注

            'fba_instant_num'       => 'sum(fba_instant_num) as fba_instant_num',   //fba在库
            'fba_transit_num'       => 'sum(fba_transit_num) as fba_transit_num',   //fba在途
            'cn_instant_num'        => 'sum(cn_instant_num) as cn_instant_num',     //国内在库
            'cn_transit_num'        => 'sum(cn_transit_num) as cn_transit_num',     //国内在途
            'os_instant_num'        => 'sum(os_instant_num) as os_instant_num',     //海外仓在库
            'os_transit_num'        => 'sum(os_transit_num) as os_transit_num',     //海外仓在途
            'dispense_num'          => 'sum(dispense_num) as dispense_num',     //分配数量
            'dispense_surplus_num'  => 'sum(dispense_surplus_num) as dispense_surplus_num', //分配剩余数量
            'stock_total'           => 'sum(stock_total) as stock_total',           //库存总量

            'cn_pulic_instant_num'  => 'sum(cn_pulic_instant_num) as cn_pulic_instant_num', //公共在库数量（public）
            'cn_stock_total'        => 'sum(cn_stock_total) as cn_stock_total',             //中国库存总量（public）
            'overstock_num'         => 'sum(overstock_num) as overstock_num',               //备货推荐和总积压库存
            'divert_overstock_num'  => 'sum(divert_overstock_num) as divert_overstock_num', //总库存可挪用积压
            'divert_instant_num'    => 'sum(divert_instant_num) as divert_instant_num',     //中国在库库存可挪用积压
            'divert_transit_num'    => 'sum(divert_transit_num) as divert_transit_num',     //中国在途库存可挪用积压
            'defer_stock_num'       => 'sum(defer_stock_num) as defer_stock_num',           //阶段性可挪用在库存

            'unit_price'     => 'unit_price as unit_price',             //采购单价
            'purchase_cycle' => 'purchase_cycle as purchase_cycle',     //产品生产周期(天)
            'sea_day'        => 'sea_day as sea_day',                   //海运时间(天)
            'air_day'        => 'air_day as air_day',                   //空运时间(天)
        ];

        $title2 = [];
        for($i = 0; $i < StockupAreaSkuEstimate::NEW_ESTIMATE_NUM; $i++){
            $title2['estimate_num'.$i] = 'sum(estimate_num'.$i.') as estimate_num'.$i;
        }
        $title3 = [];
        for($i = 0; $i < StockupAreaSkuEstimate::NEW_ESTIMATE_NUM; $i++){
            $title2['cn_delivery_num'.$i] = 'sum(cn_delivery_num'.$i.') as cn_delivery_num'.$i;
        }
        $title4 = [];
        for($i = 0; $i < StockupAreaSkuEstimate::NEW_ESTIMATE_NUM; $i++){
            $title2['stock_plan'.$i] = 'sum(stock_plan'.$i.') as stock_plan'.$i;
        }
        $title = array_merge($title1,$title2,$title3,$title4);


        $sqlColumnTitle = array_keys($title);   //sql列名
        $sqlColumnValue = array_values($title); //sql别名（汇总字段别名）
        $sql = implode($sqlColumnValue, ',') ?? '*'; //SQL查询参数字段

        return [$sqlColumnTitle, $sqlColumnValue, $sql];
    }
    /*public static function setSqlColumnBack(){

        $title1 = [
            'classify_id',      //品类ID
            'area_id',          //站点ID
            'psku_id',          //产品ID
            'sum(avg3) as avg3',     //3天avg
            'sum(avg7) as avg7',     //7天avg
            'sum(avg15) as avg15',   //15天avg
            'sum(avg30) as avg30',   //30天avg
            'sum(avg) as avg',       //avg

            'sum(current_sale_ratio) as current_sale_ratio', //旺季销售比例
            'sum(volume3_avg) as volume3_avg',         //近3天平均销量
            'sum(volume30_avg) as volume30_avg',         //近30天平均销量
            'sum(volume30_ratio) as volume30_ratio',         //近30天销售比例
            'sum(ratio) as ratio',                           //确定后的销售比例
            'sum(estimate_total) as estimate_total',     //预估总量
            'sum(estimate_growth_rate) as estimate_growth_rate', //同期增长率

            'sum(abroad_recommend_num) as abroad_recommend_num',   //推荐海外仓发货数量
            'sum(abroad_reality_num) as abroad_reality_num',  //实际海外仓发货数量
            'sum(recommend_num) as recommend_num',  //推荐备货数量
            'recommend_remark as recommend_remark', //推荐说明
            'sum(apply_num) as apply_num',  //申请数量
            'apply_remark as apply_remark', //申请备注
            'sum(approval_num) as approval_num',  //审批数量
            'approval_remark as approval_remark', //审批备注
            'sum(confirm_num) as confirm_num',  //确认数量
            'confirm_remark as confirm_remark', //确认备注

            'sum(fba_instant_num) as fba_instant_num',   //fba在库
            'sum(fba_transit_num) as fba_transit_num',   //fba在途
            'sum(cn_instant_num) as cn_instant_num',     //国内在库
            'sum(cn_transit_num) as cn_transit_num',     //国内在途
            'sum(os_instant_num) as os_instant_num',     //海外仓在库
            'sum(os_transit_num) as os_transit_num',     //海外仓在途
            'sum(dispense_num) as dispense_num',     //分配数量
            'sum(dispense_surplus_num) as dispense_surplus_num', //分配剩余数量
            'sum(stock_total) as stock_total',           //库存总量

            'sum(cn_pulic_instant_num) as cn_pulic_instant_num', //公共在库数量（public）
            'sum(cn_stock_total) as cn_stock_total',             //中国库存总量（public）
            'sum(overstock_num) as overstock_num',               //备货推荐和总积压库存
            'sum(divert_overstock_num) as divert_overstock_num', //总库存可挪用积压
            'sum(divert_instant_num) as divert_instant_num',     //中国在库库存可挪用积压
            'sum(divert_transit_num) as divert_transit_num',     //中国在途库存可挪用积压
            'sum(defer_stock_num) as defer_stock_num',           //阶段性可挪用在库存

            'unit_price as unit_price',             //采购单价
            'purchase_cycle as purchase_cycle',     //产品生产周期(天)
            'sea_day as sea_day',                   //海运时间(天)
            'air_day as air_day',                   //空运时间(天)
        ];
        $title2 = [];
        for ($i=0; $i<=8; $i++){
            //预估（月）
            $title2[] = 'sum(estimate_num'.$i .') as estimate_num'.$i;
            //中国发货需求（月）
            $title2[] = 'sum(cn_delivery_num'.$i .') as cn_delivery_num'.$i;
            //库存分配（月）
            $title2[] = 'sum(stock_plan'.$i .') as stock_plan'.$i;
        }

        $columnArray = array_merge($title1,$title2);

        return implode($columnArray, ',') ?? '*';
    }*/

    /**
     * 获取库存信息（总表）
     * @param $item
     * @return mixed
     */
    public static function setStockupColumn($item){

        $params = [];

        $areaPskuArray = explode('_', $item->area_psku); //area_psku (sku基础值)
        $areaId = $areaPskuArray[0];
        $pskuId = $areaPskuArray[1];
        $params['area_id'] = $areaId;
        $params['psku_id'] = $pskuId;

        $productSku = ProductSku::getModelById($pskuId);
        $classifyId = $productSku->classify_id;
        $item->classify_id = $classifyId;
        $params['classify_id'] = $classifyId;

        //销售旺季比例（季节性）
        $currentSaleRatio = self::getSeasonRatioData($classifyId);
        $item->current_sale_ratio = $currentSaleRatio;
        $params['current_sale_ratio'] = $currentSaleRatio;

        //近30天销售比例（sku）
        $volumeRatio30 = self::getVolume30($classifyId, $pskuId);
        $item->volume30_ratio = $volumeRatio30;
        $params['volume30_ratio'] = $volumeRatio30;

        //公共在库数量 (PUBLIC)
        $item->cn_pulic_instant_num = PublicCn::getInstant($pskuId);
        $params['cn_pulic_instant_num'] = PublicCn::getInstant($pskuId);

        //sku销售预估总量
        $estimateTotal = 0;
        for ($i = 0; $i <= 8; $i++){
            $estimateTotal += $item->estimate_num{$i} ?? 0;
        }
        $item->estimate_total = $estimateTotal ?? 0;
        $params['estimate_total'] = $estimateTotal ?? 0;

        //sku库存总量 (fba在库+fba在途+国内在库+国内在途+海外仓在库+海外仓在途)
        $stockTotal = $item->fba_instant_num + $item->fba_transit_num + $item->cn_instant_num + $item->cn_transit_num + $item->os_instant_num + $item->os_transit_num;
        $item->stock_total = $stockTotal ?? 0;
        $params['stock_total'] = $stockTotal ?? 0;

        //备货推荐和总积压库存
        $overstockNum = $estimateTotal - $stockTotal; //总积压库存 = 预估量 - 库存总量
        $item->overstock_num = $overstockNum; //备货推荐和总积压库存 = (积压库存 < 0 ? 积压库存 : 推荐备货数量)
        $params['overstock_num'] = $overstockNum;

        //中国库存总量
        $cnStockTotal = $item->cn_instant_num + $item->cn_transit_num; //中国库存（中国在库+中国在途）
        $item->cn_stock_total = $cnStockTotal;
        $params['cn_stock_total'] = $cnStockTotal;

        //总库存可挪用积压
        if ($overstockNum > 0) {
            $divertOverstockNum = 0;
        }else{
            if ($cnStockTotal > $overstockNum) {
                $divertOverstockNum = $overstockNum; //备货推荐和总积压库存
            }else{
                $divertOverstockNum = $cnStockTotal; //中国库存总量
            }
        }
        $item->divert_overstock_num = $divertOverstockNum; //总库存可挪用积压 = 中国库存 > 备货推荐和总积压库存 ? 推荐数量 : 中国库存;
        $params['divert_overstock_num'] = $divertOverstockNum;

        //中国在库库存可挪用积压
        if ($overstockNum > $item->cn_instant_num) {
            $divertInstantNum = $item->cn_instant_num; //中国在库库存
        }else{
            $divertInstantNum = $overstockNum; //可挪用积压
        }
        $item->divert_instant_num = $divertInstantNum; //在库库存可挪用积压 = 总库存可挪用积压 > 中国在库 ? 中国在库 : 总库存可挪用积压;
        $params['divert_instant_num'] = $divertInstantNum;

        //中国在途库存可挪用积压
        if ($overstockNum > $item->cn_transit_num) {
            $divertTransitNum = $item->cn_transit_num; //中国在途库存
        }else{
            $divertTransitNum = $overstockNum;
        }
        $item->divert_transit_num = $divertTransitNum; //在途库存可挪用积压 = 总库存可挪用积压 > 中国在途 ? 中国在途 : 总库存可挪用积压;
        $params['divert_transit_num'] = $divertTransitNum;

        //阶段性可挪用在库存()
        //备货周期 = 产品采购时间 + 物流海运时间
        //阶段性可挪用在库存 = 总库存可挪用积压 - 备货周期
        $stockingSetDate = StockingSetDate::getModel($areaId, $classifyId);
        if ($stockingSetDate) {
            $stockupCycle = $stockingSetDate->purchase_cycle + $stockingSetDate->sea_day; //备货周期(天数) = 产品采购时间 + 物流海运时间
            $params['purchase_cycle'] = $stockingSetDate->purchase_cycle;
            $params['sea_day'] = $stockingSetDate->sea_day ?? 0;
            $params['air_day'] = $stockingSetDate->air_day ?? 0;

            //阶段性可挪用在库存
            $cycleNum = Stockup::_getAvailableEstimateNum($item, $stockupCycle); //备货周期库存(库存警戒线)
            $deferStockNum = $overstockNum - $cycleNum; //阶段性可挪用在库存 = 总库存可挪用积压 - 备货周期
            $item->defer_stock_num = $deferStockNum > 0 ? $deferStockNum : 0;
            $params['defer_stock_num'] = $deferStockNum > 0 ? $deferStockNum : 0;
        }

        //中国仓库发货需求
        $totalStockSum = $item->fba_instant_num + $item->fba_transit_num + $item->os_instant_num + $item->os_transit_num; //fba+海外仓库存
        for ($i = 0; $i < StockupAreaSkuEstimate::NEW_ESTIMATE_NUM; $i++){

            //首月发货需求数量
            $cnFristMonthNumber = $item->estimate_num0 - $totalStockSum; //首月发货需求数量 = （首月发货预估数量 - 库存）
            if ($cnFristMonthNumber <= 0) {
                $params['cn_delivery_num0'] = $cnFristMonthNumber;
            }else{
                $params['cn_delivery_num0'] = 0;
            }

            //其它月份发货需求数量
            if ($i > 0) {
                $currentMonthEstimateNum = $item->estimate_num{$i} ?? 0;
                $params['cn_delivery_num'.$i] = $currentMonthEstimateNum; //初始化月份发货需求数量 （月份发货需求数量 = 月份预估数量）

                if ($params['cn_delivery_num'.($i-1)] < 0){ //上月发货需求数量 < 0, 则之前月份预估数量累加当月发货需求数量。

                    for ($j = 1; $j <= $i; $j++){
                        //当月发货需求数量 = (当月 + 小于当前月份的其它月份发货需求数量 + 库存)
                        $params['cn_delivery_num'.$i] = $params['cn_delivery_num'.$j] + round($cnFristMonthNumber/2) - $totalStockSum;
                    }
                }else{
                    //当月发货需求数量 = 当月预估
                    $params['cn_delivery_num'.$i] = $currentMonthEstimateNum;
                }
            }
        }

        return json_decode(json_encode($params));
    }

    /**
     * 产品季节销售比例
     * @param $classifyId
     * @return string
     */
    public static function getSeasonRatioData($classifyId){

        $season = ProductClassify::getSeasonById($classifyId);
        if ($season == ProductClassify::SEASON_WINTER) {
            //本期（冬季）
            $currentStartTime = date('Y-09-01', time());
            if (strtotime(date('Y-m-d', time())) < strtotime($currentStartTime)) {
                $currentEndTime = date('Y-m-d', strtotime($currentStartTime . "-1 year")); //当季（冬季）时间不满足，则向前选取上季时间
            }
            $currentEndTime = date('Y-m-d', strtotime($currentStartTime . "+6 month -1 day"));

            //上期（冬季）
            $provStartTime = date('Y-m-d', strtotime($currentEndTime . "-1 year"));
            $provEndTime = date('Y-m-d', strtotime($currentEndTime . "-1 year -1 day"));
        }else{
            //本期（夏季和其他）
            $currentStartTime = date('Y-03-01', time());
            if (strtotime(date('Y-m-d', time())) < strtotime($currentStartTime)) {
                $currentEndTime = date('Y-m-d', strtotime($currentStartTime . "-1 year"));  //当季（夏季和其他）时间不满足，则向前选取上季时间
            }
            $currentEndTime = date('Y-08-30', time());

            //上期（夏季和其他）
            $provStartTime = date('Y-m-d', strtotime($currentStartTime . "-1 year"));
            $provEndTime = date('Y-m-d', strtotime($currentEndTime . "-1 year -1 day"));
        }

        //本期销量
        $currentData = self::seasonVolumeData($currentStartTime, $currentEndTime, $classifyId, $season);
        //上期销量
        $provData = self::seasonVolumeData($provStartTime, $provEndTime, $classifyId, $season);

        //最近销售旺季比例 = 本期销量/上期销量
        if ($currentData > 0 && $provData > 0) {
            $currentSaleRatio = round($currentData/$provData * 100, 2) ?? 0;
        }else{
            $currentSaleRatio = 0;
        }

        return $currentSaleRatio;
    }

    /**
     * 获取产品近30天销量
     * @param $classifyId
     * @param $pskuId
     * @return string
     */
    public static function getVolume30($classifyId, $pskuId){

        //最近30天销售比例
        $stratTime = date('Y-m-d', strtotime("-30 day"));
        $endTime = date('Y-m-d', strtotime("-1 day"));
        //品类近30天总量
        $classVolume30 = self::seasonVolumeData($stratTime, $endTime, $classifyId) ?? 0;
        //sku近30天总量
        $skuVolume30 = self::skuVolumeData($stratTime, $endTime, $pskuId) ?? 0;

        //30天销售比例 = SKU近30天销量/品类近30天销量
        if ($classVolume30 > 0) {
            $radio = $skuVolume30/$classVolume30 * 100 ?? 0;
        }else{
            $radio = 0;
        }

        return $radio;
    }

    /**
     * 产品品类的销量数据
     * @param $startTime
     * @param $endTime
     * @param $classifyId
     * @param $season
     * @return int|mixed
     */
    public static function seasonVolumeData($startTime, $endTime, $classifyId = null, $season = null){

        $query = DailyVolume::query()->whereBetween('report_date', [$startTime, $endTime]);
        if ($classifyId) $query->where('classify_id', $classifyId);
        if ($season) $query->where('season', $season);

        return $query->sum('volume');
    }

    /**
     * 产品的销量数据
     * @param $startTime
     * @param $endTime
     * @param null $pskuId
     * @return int|mixed
     */
    public static function skuVolumeData($startTime, $endTime, $pskuId = null){

        $query = DailyVolume::query()->whereBetween('report_date', [$startTime, $endTime]);
        if ($pskuId) $query->where('psku_id', $pskuId);

        return $query->sum('volume');
    }

}
